package com.liuhongwei.test.plugin;

import com.liuhongwei.test.bean.Constants;
import com.liuhongwei.test.bean.TableInfo;
import com.liuhongwei.test.builder.BuildAssemble;
import com.liuhongwei.test.builder.BuildBase;
import com.liuhongwei.test.builder.BuildController;
import com.liuhongwei.test.builder.BuildExtendMapper;
import com.liuhongwei.test.builder.BuildExtendMapperXml;
import com.liuhongwei.test.builder.BuildQuery;
import com.liuhongwei.test.builder.BuildService;
import com.liuhongwei.test.builder.BuildServiceImpl;
import com.liuhongwei.test.builder.BuildTable;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GeneratorMain {

    public static void main(String[] args) throws URISyntaxException {
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("my-generator/generatorConfig.xml");
            InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
            //支持项目路径为中文的解析器
            ConfigurationParserCH cp = new ConfigurationParserCH(warnings);
            Configuration config = cp.parseConfiguration(reader);

            List<Context> contexts = config.getContexts();
            for (Context context : contexts) {
                System.out.println(context);
            }
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);

            List<TableInfo> tables = BuildTable.getTable(Constants.NAME_TABLE, Constants.TABLE_NOTICE);
            tables.forEach(System.out::println);
            for (TableInfo table : tables) {
                BuildAssemble.execute(table);
                BuildQuery.execute(table);
                BuildExtendMapper.execute(table);
                BuildExtendMapperXml.execute(table);
                BuildService.execute(table);
                BuildServiceImpl.execute(table);
                BuildController.execute(table);
            }
            log.info("生成完毕");
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
